package org.apache.ibatis.usage.base;

import org.apache.ibatis.usage.model.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @Name BaseJdbcOperator
 * @Description: 传统数据库连接操作实现过程
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-04-23 17:09:47
 **/
public class BaseJdbcOperator {

    public static void run() throws Exception {
        // 数据库连接信息
        String url = "jdbc:mysql://127.0.0.1:3306/mybatis-usage?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false";
        String username = "root";
        String password = "123456";

        User user = User.builder().name("杰克").build();
        // 传统数据库连接操作
        // 1. 加载驱动程序
        Class.forName("com.mysql.jdbc.Driver");
        // 2. 建立数据库连接
        Connection con = DriverManager.getConnection(url, username, password);
        // 3. 创建 SQL 语句并执行
        Statement statement = con.createStatement();
        ResultSet resultSet = statement.executeQuery("SELECT * FROM `user` WHERE name = \'" + user.getName() + "\';");
        // 4. 处理返回结果
        List<User> users = new ArrayList<>();
        while (resultSet.next()) {
            User u = User.builder().id(resultSet.getInt("id"))
                    .name(resultSet.getString("name"))
                    .email(resultSet.getString("email"))
                    .age(resultSet.getInt("age"))
                    .sex(resultSet.getInt("sex"))
                    .schoolName(resultSet.getString("schoolName")).build();
            users.add(u);
        }
        System.out.println(users);
        // 5. 关闭连接，释放资源
        statement.close();
    }

}

